"""Classes related to saving data such as user ID and API key and the
Skill Tree as a Python pickle to remember data between sessions."""
from cPickle import load, dump
import sys

class Pickle():
    """Parent class for things that need pickling. Shouldn't be used
 directly."""
    def __init__(self, filename):
        self.data = {}
        self.filename = filename

    def loadData(self):
        """Loads pickled data from self.filename."""
        try:
            in_pickle = open(self.filename,"rb")
            self.data = load(in_pickle)
        except IOError, error:
            raise IOError, error
        except:
            print "Unexpected error:", sys.exc_info()[0]
            raise
        else:
            in_pickle.close()

    def saveData(self):
        """Saves pickled data to self.filename."""
        try:
            out_pickle = open(self.filename,"wb")
            dump(self. data, out_pickle, -1)
        except IOError, error:
            raise IOError, error
        except:
            print "Unexpected error:", sys.exc_info()[0]
            raise
        else:
            out_pickle.close()


class ConfigPickle(Pickle):
    """Handles reading, writing and storing account and character data."""
    def __init__(self):
        Pickle.__init__(self, "config.pickle")

    def setAccount(self, uid, apikey, cids):
        """Adds or modifies an account to be stored, including all
 characters within the account."""
        self.data[uid] = {
                "apikey": apikey,
                "cids": cids
        }
        print self.data

    def getCharParams(self, uid, cid):
        """Fetches a given character's data given the user ID and character
 ID. Returned object is urlencoded for use as POST parameters for
 fetching data from the Eve API."""
        # Test for existence of required data
        try:
            assert uid in self.data, "Account not found."
            assert cid in self.data[uid]["cids"], "Character not found."
            assert "apikey" in self.data[uid], "API key not found."
        except AssertionError, strerror:
            print "Error: %s" % strerror
            raise

        # Build urlencoded POST data
        params = {
            'characterID': cid,
            'userID': uid,
            'apikey': self.data[uid]["apikey"]
        }

        return params

    def chars(self, uid):
        """Returns a list of character IDs given a user id."""
        return self.data[uid]["cids"]

    def uids(self):
        """Returns a list of uids saved in the ConfigPickle."""
        return self.data.keys()

class SkillPickle(Pickle):
    """Handles reading and writing a pickled SkillTree. This avoids having
to refetch and reparse the SkillTree.xml every time for no reason."""
    def __init__(self):
        Pickle.__init__(self, "SkillTree.pickle")
